<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\SetUserUp;
use app\models\user\User;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class PerformanceController extends H5Controller
{
    // 业绩
    public function actionIndex()
    {
        $box = $this->_getBox($this->user->id);

        $ids = Chain::getChildrenAllQuick($this->user->id, []);
        $ids = ArrayHelper::getColumn($ids, 'id');

        // 没有算自己的
        $team = $this->_getBox($ids);

        $set = SetUserUp::getLastOne();
        $user = User::findOne(['id' => $this->user->id]);

        $amount1 = $set->box1_award * $set->box1;
        $amount2 = $set->box2_award * $set->box2;
        $amount3 = $set->box3_award * $set->box3;
        $amount4 = $set->box4_award * $set->box4;

        $x = [
            'box1' => $set->box1,
            'box2' => $set->box2,
            'box3' => $set->box3,
            'box4' => $set->box4,
            'text1' => $user->sell_1 > 0 ? '完成, 奖励: ' . ($amount1 - 0) : '未完成',
            'text2' => $user->sell_2 > 0 ? '完成, 奖励: ' . ($amount2 - $amount1) : '未完成',
            'text3' => $user->sell_3 > 0 ? '完成, 奖励: ' . ($amount3 - $amount2 - $amount1) : '未完成',
            'text4' => $user->sell_4 > 0 ? '完成, 奖励: ' . ($amount4 - $amount3 - $amount2 - $amount1) : '未完成',
        ];

        return $this->successEncode([
            'user' => $user->toArray(),
            'box' => $box,
            'team' => $team,
            'set' => $x
        ]);

    }

    protected function _getBox($user_ids)
    {
        $order_ids = Order::find()
            ->where(['user_id' => $user_ids])
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->select(['id'])
            ->column();

        $items = OrderItem::find()
            ->where(['order_id' => $order_ids])
            ->with(['product'])
            ->all();
        $box = 0;
        foreach ($items as $item) {
            if ($item['product']) {

                // 84000 不算
                if ($item['product']['price'] == 84000) {
                    continue;
                }

                $box += $item['product']['store'] * $item['quantity'];
            }
        }

        return  $box;
    }
}